<!-- 模块分解tab -->
<template>
  <div class="functional-decomposition">
    <slot></slot>
    <el-tree
      :data="dataSource"
      ref="treeRef"
      :show-checkbox="isShowCheckbox"
      node-key="id"
      :check-strictly="true"
      highlight-current
      default-expand-all
      draggable
      :allow-drag="allowDrag"
      :allow-drop="allowDrop"
      @node-drop="handleNodeDrop"
      :expand-on-click-node="false"
      @node-click="handleNodeClick"
      @check="handleNodeCheck"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <!-- 1. 左边 模块目录、模块描述、添加按钮 -->
          <span>
            <el-popover placement="right" :title="data.label" :width="400" trigger="click">
              <template #reference>
                <span class="content">
                  {{ data.label }}
                </span>
              </template>
              <template #default>
                <div class="describe">
                  <div class="title">{{ data.describe }}</div>
                  <el-table
                    :data="tableData"
                    :row-key="(row: any) => row.activityId"
                    style="width: 100%; margin: 0 auto; border: #d0d0d0 1px solid"
                    max-height="200"
                    @selection-change="handleSelectionChange(data.id, $event)"
                  >
                    <el-table-column v-if="isShowCheckbox" type="selection" width="55">
                    </el-table-column>
                    <el-table-column label="活动状态" prop="activityStatus">
                      <template #default="scope">
                        <el-tag :type="getTagType(scope.row.activityStatus)">
                          {{ getActivityStatusText(scope.row.activityStatus) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="活动名称" prop="activityName" />
                    <el-table-column label="活动描述" prop="activityDescribe" />
                  </el-table>
                </div>
              </template>
            </el-popover>
            <el-button
              v-if="showButton"
              type="primary"
              text
              @click="appendFunc(data)"
              icon="CirclePlus"
            />
          </span>

          <!-- 2. 右边 编辑或删除按钮 在创建任务的模块的选择时为多选框-->
          <span v-if="showButton">
            <el-button
              type="info"
              text
              icon="Edit"
              @click="editInfoFunc(data.id, data.label, data.describe)"
            >
              编辑
            </el-button>
            <el-tooltip
              content="此模块不允许删除"
              placement="top-start"
              :disabled="data.id !== props.project?.projectId"
            >
              <el-button
                type="danger"
                text
                icon="Delete"
                @click="removeFunc(node, data)"
                :disabled="data.id === props.project?.projectId"
              >
                删除
              </el-button>
            </el-tooltip>
          </span>
        </span>
      </template>
    </el-tree>
  </div>
  <!-- 抽屉组件 -->
  <div class="drawer">
    <info-drawer
      :isShowDrawer="isShowDrawer"
      :modelId="currentId"
      :modelName="currentLabel"
      :modelDescribe="currentDescribe"
      @update:is-show-drawer="updateShowDrawer"
      @update:model="updateModel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import infoDrawer from './c-cpns/info-drawer.vue'
import { functionalAppend, functionalRemove } from '@/utils/functional-operation'
import { moveModelRequest } from '@/service/model/model'
import { buildTreeData } from '@/utils/treeDataBuilder'
import { ElMessage, ElTree } from 'element-plus'
import { getActivityByModel } from '@/service/activity/activity'
import { useTaskStore } from '../../store/task/task'
const  store = useTaskStore()
// 变量
// 接收父组件传递的值
const props = defineProps({
  project: Object,
  showButton: {
    type: Boolean,
    default: true
  },
  isShowCheckbox: {
    type: Boolean,
    default: false
  }
})
const dataSource = ref<Tree[]>([])
const emit = defineEmits(['updateProject'])
interface activity {
  activityId: string
  activityStatus: string
  activityName: string
  activityDescribe: string
  modelId: string
}
const tableData = ref([] as activity[])
const getActivityList = async (modelId: string) => {
  const res = await getActivityByModel(modelId)
  tableData.value = res.data
  console.log('tableData:', tableData.value)
}
const getTagType = (status: number) => {
  switch (status) {
    case 1:
      return 'primary'
    case 2:
      return 'success'
    case 3:
      return 'danger'
    default:
      return 'info'
  }
}

const getActivityStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '待发布'
    case 2:
      return '实施中'
    case 3:
      return '已完成'
    default:
      return '未知状态'
  }
}
watchEffect(() => {
  if (props.project) {
    dataSource.value = buildTreeData(
      props.project.modelVOS,
      props.project.projectName,
      props.project.projectDescribe,
      props.project.projectState,
      props.project.projectId
    )
  }
})
// const parentNode = dataSource.value[0]?.id
const isShowDrawer = ref(false)
const currentId = ref('-1')
const currentLabel = ref('')
const currentDescribe = ref('')
// 函数
// 接收子组件发射过来的事件并实现
const updateShowDrawer = () => {
  isShowDrawer.value = false
}
const updateModel = (label: string, describe: string) => {
  const model = dataSource.value.find((item) => item.id === currentId.value)
  if (model) {
    model.label = label
    model.describe = describe
  }
  emit('updateProject', dataSource.value)
}
// 编辑功能描述
const editInfoFunc = (id: string, label: string, describe: string) => {
  isShowDrawer.value = true
  currentId.value = id
  currentLabel.value = label
  currentDescribe.value = describe
}
// 点击节点将显示功能描述
const selectedNode = ref(new Set<string>())
const handleNodeClick = async (data: any) => {
  await getActivityList(data.id)
}
//选择节点
const handleNodeCheck = (data: any) => {
  if (!selectedNode.value.has(data.id)) {
    selectedNode.value.add(data.id)
  } else {
    selectedNode.value.delete(data.id)
    handleSelectionChange(data.id, [])
  }
  // 同步树节点的勾选状态
  treeRef.value?.setChecked(data.id, selectedNode.value.has(data.id), false)
  console.log('Selected Nodes:', Array.from(selectedNode.value))
  store.taskMsg.list = Array.from(selectedNode.value)
}

// 处理选择变化
const treeRef = ref<InstanceType<typeof ElTree>>()
const selectedActivities = ref(new Set<string>())
function handleSelectionChange(modelId: string, selectedItems: any[]) {
  let isAnySelected = false
  tableData.value.forEach((activity) => {
    if (selectedItems.some((item) => item.activityId === activity.activityId)) {
      selectedActivities.value.add(activity.activityId)
      isAnySelected = true
    } else {
      selectedActivities.value.delete(activity.activityId)
    }
  })
  console.log('Selected Activities:', Array.from(selectedActivities.value))
  if (isAnySelected) {
    selectedNode.value.add(modelId)
  }
  // 更新对应模块的勾选状态
  const currentNode = treeRef.value?.getNode(modelId)
  if (currentNode) {
    // 如果表格中有选中的活动，则勾选模块，否则取消勾选模块
    treeRef.value?.setChecked(modelId, true, false)
  }
  console.log('Selected Nodes:', Array.from(selectedNode.value))
  store.taskMsg.list = Array.from(selectedNode.value)
}

// 添加模块按钮
const appendFunc = (data: Tree) => {
  functionalAppend(data, emit)
}

// 删除模块按钮
const removeFunc = (node: Node, data: Tree) => {
  functionalRemove(node, data, emit)
}

// 判断节点是否可拖拽
//showButton为false时，所有节点都不可以拖拽
function allowDrag(draggingNode: any) {
  if (!props.showButton) {
    return false
  }
  return draggingNode.data.id !== props.project?.projectId // 根节点不能拖拽
}

// 判断节点是否可以放置
function allowDrop(draggingNode: any, dropNode: any, type: any) {
  // 不能与根节点同级
  if (type !== 'inner' && dropNode.data.parentId === '-1') {
    return false
  }
  // 允许放置
  return true
}
// 移动节点
const handleNodeDrop = async (draggingNode: any, dropNode: any, dropType: any) => {
  let newParentId = dropNode.data.id // 默认放置为子节点
  if (dropType === 'before' || dropType === 'after') {
    newParentId = dropNode.data.parentId // 如果是放置在同一级别，更新为相同的父ID
  }
  try {
    await moveModelRequest({
      modelId: draggingNode.data.id,
      parentId: newParentId
    })
    emit('updateProject', dataSource.value)
    ElMessage.success('模块移动成功')
  } catch (error) {
    ElMessage.error(`模块移动失败: ${error}`)
  }
}
</script>

<style lang="less" scoped>
.functional-decomposition {
  padding-left: 20px;
  .state {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 10px;
  }
  .info {
    font-size: 14px;
    margin-left: 30px;
    cursor: pointer;
  }
  .el-button {
    margin-right: 30px;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 16px;
    padding-right: 30px;
    .content {
      margin-left: 10px;
    }
  }
  img {
    width: 100px;
  }
}
</style>
